package com.gaobug.base.config.mq;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbitmq配置加载
 *
 * @author hzq
 * @date 2022/3/21
 */
@Configuration
@EnableConfigurationProperties({RabbitMqProperties.class})
@ConditionalOnProperty(prefix = RabbitMqProperties.PREFIX, name = "enable", havingValue = "true")
public class RabbitMqAutoConfiguration {

    /**
     * 装配队列
     */
    @Bean("rabbitMqFactory")
    @ConditionalOnMissingBean
    public RabbitMqFactory rabbitMqConfiguration(RabbitAdmin rabbitAdmin, RabbitMqProperties properties) {
        RabbitMqFactory rabbitMqFactory = new RabbitMqFactory(rabbitAdmin, properties.getQueueConfig());
        // 初始化
        rabbitMqFactory.assemblyQueue();
        return rabbitMqFactory;
    }

    /**
     * 注册rabbitAdmin
     */
    @Bean
    @ConditionalOnMissingBean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * 注册rabbitMQ的Connection
     */
    @Bean
    @ConditionalOnMissingBean
    public ConnectionFactory connectionFactory(RabbitMqProperties properties) {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setAddresses(properties.getAddresses());
        cachingConnectionFactory.setUsername(properties.getUsername());
        cachingConnectionFactory.setPassword(properties.getPassword());
        cachingConnectionFactory.setVirtualHost(properties.getVirtualHost());
        return cachingConnectionFactory;
    }

    /**
     * 注册监听容器 手动确认消费模式
     */
    @Bean
    @ConditionalOnMissingBean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }
}

